<template>
  <a-select v-model:value="trainCode" show-search allowClear :placeholder="_placeholder"
            :filter-option="filterTrainCodeOption" @change="onChange" :style="`width:${_width}`">
    <a-select-option v-for="item in trains" :key="item.code" :value="item.code"
                     :label="item.code+' | '+item.start+' ~ '+item.end">
      {{ item.code }} | {{ item.start }} ~ {{ item.end }}
    </a-select-option>
  </a-select>
</template>

<script setup lang="ts" name="TrainSelect">
import {onMounted, ref} from "vue";
import {queryAll} from "@/api/base/train";
import {notification} from "ant-design-vue";
import {isEmpty} from "@/utils/tools.ts";

const trainCode = defineModel<string|undefined>("trainCode");

const trains = ref<any[]>([]);

const props = defineProps(["width","placeholder"]);

const _placeholder = ref<string>(props.placeholder);
if (isEmpty(_placeholder.value)) {
  _placeholder.value = "请选择查询车次"
}

const _width = ref<string>(props.width);
if (isEmpty(_width)) {
  _width.value = "100%"
}


const emit = defineEmits(["change"])

// @ts-ignore
const filterTrainCodeOption = (input: string, option: any) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

const onChange = (value: string) => {
  let selectValue = undefined;
  trains.value.forEach((item: any) => {
    if (item.code === value) {
      selectValue = item;
    }
  })
  emit("change", selectValue);
}
const getAllTrains = async () => {
  try {
    const result = await queryAll();
    if (result.success) {
      trains.value = result.data as any;
    } else {
      notification.error({message: "获取所有车次失败", description: result.message});
    }
  } catch (e: any) {
    notification.error({message: "获取所有车次失败", description: e.message});
  }
}

onMounted(() => {
  getAllTrains()
})

</script>


<style scoped>

</style>